//import websdk from "@/utils/hx/uni_sdk4.0.7";
import websdk from "@/utils/hx/easemob-chat-4.1.5";
import config from "@/utils/hx/WebIMConfig";

console.group = console.group || {};
console.groupEnd = console.groupEnd || {};
var window = {};
let WebIM = window.WebIM = uni.WebIM = websdk;
window.WebIM.config = config; //var DOMParser = window.DOMParser = xmldom.DOMParser;
//let document = window.document = new DOMParser().parseFromString("<?xml version='1.0'?>\n", "text/xml");

WebIM.isDebug = function(option) {
    if (option) {
        WebIM.config.isDebug = option.isDebug;
        openDebug(WebIM.config.isDebug);
    }

    function openDebug(value) {
        function ts() {
            var d = new Date();
            var Hours = d.getHours(); // 获取当前小时数(0-23)

            var Minutes = d.getMinutes(); // 获取当前分钟数(0-59)

            var Seconds = d.getSeconds(); // 获取当前秒数(0-59)

            return (Hours < 10 ? "0" + Hours : Hours) + ":" + (Minutes < 10 ? "0" + Minutes : Minutes) + ":" + (
              Seconds < 10 ? "0" + Seconds : Seconds) + " ";
        }
    }
};
/**
 * Set autoSignIn as true (autoSignInName and autoSignInPwd are configured below),
 * You can auto signed in each time when you refresh the page in dev model.
 */


WebIM.config.autoSignIn = false;

if (WebIM.config.autoSignIn) {
    WebIM.config.autoSignInName = "lwz2";
    WebIM.config.autoSignInPwd = "1";
} // var stropheConn = new window.Strophe.Connection("ws://im-api.easemob.com/ws/", {
//                 inactivity: 30,
//                 maxRetries: 5,
//                 pollingTime: 4500
//             });
//
// stropheConn.connect(
//   '$t$' + 'YWMtmbQEBKKIEeaGmMtXyg5n1wAAAVlkQvGO2WOJGlMCEJKM4VV9GCMnb_XLCXU',
//   function() {
//     console.log(arguments, 'ggogogo');
//   }, stropheConn.wait, stropheConn.hold);


WebIM.parseEmoji = function(msg) {
    if (typeof WebIM.Emoji === "undefined" || typeof WebIM.Emoji.map === "undefined") {
        return msg;
    }

    var emoji = WebIM.Emoji,
      reg = null;
    var msgList = [];
    var objList = [];

    for (var face in emoji.map) {
        if (emoji.map.hasOwnProperty(face)) {
            while (msg.indexOf(face) > -1) {
                msg = msg.replace(face, "^" + emoji.map[face] + "^");
            }
        }
    }

    var ary = msg.split("^");
    var reg = /^e.*g$/;

    for (var i = 0; i < ary.length; i++) {
        if (ary[i] != "") {
            msgList.push(ary[i]);
        }
    }

    for (var i = 0; i < msgList.length; i++) {
        if (reg.test(msgList[i])) {
            var obj = {};
            obj.data = msgList[i];
            obj.type = "emoji";
            objList.push(obj);
        } else {
            var obj = {};
            obj.data = msgList[i];
            obj.type = "txt";
            objList.push(obj);
        }
    }

    return objList;
};

WebIM.time = function() {
    var date = new Date();
    var Hours = date.getHours();
    var Minutes = date.getMinutes();
    var Seconds = date.getSeconds();
    var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + (Hours < 10 ? "0" +
      Hours : Hours) + ":" + (Minutes < 10 ? "0" + Minutes : Minutes) + ":" + (Seconds < 10 ? "0" + Seconds :
      Seconds);
    return time;
};

WebIM.Emoji = {
    path: "/static/images/faces/",
    map: {
        "[):]": "ee_1.png",
        "[:D]": "ee_2.png",
        "[;)]": "ee_3.png",
        "[:-o]": "ee_4.png",
        "[:p]": "ee_5.png",
        "[(H)]": "ee_6.png",
        "[:@]": "ee_7.png",
        "[:s]": "ee_8.png",
        "[:$]": "ee_9.png",
        "[:(]": "ee_10.png",
        "[:'(]": "ee_11.png",
        "[<o)]": "ee_12.png",
        "[(a)]": "ee_13.png",
        "[8o|]": "ee_14.png",
        "[8-|]": "ee_15.png",
        "[+o(]": "ee_16.png",
        "[|-)]": "ee_17.png",
        "[:|]": "ee_18.png",
        "[*-)]": "ee_19.png",
        "[:-#]": "ee_20.png",
        "[^o)]": "ee_21.png",
        "[:-*]": "ee_22.png",
        "[8-)]": "ee_23.png",
        "[del]": "btn_del.png",
        "[(|)]": "ee_24.png",
        "[(u)]": "ee_25.png",
        "[(S)]": "ee_26.png",
        "[(*)]": "ee_27.png",
        "[(#)]": "ee_28.png",
        "[(R)]": "ee_29.png",
        "[({)]": "ee_30.png",
        "[(})]": "ee_31.png",
        "[(k)]": "ee_32.png",
        "[(F)]": "ee_33.png",
        "[(W)]": "ee_34.png",
        "[(D)]": "ee_35.png"
    }
};
WebIM.EmojiObj = {
    // 相对 emoji.js 路径
    path: "../static/images/faces/",
    map1: {
        "[):]": "ee_1.png",
        "[:D]": "ee_2.png",
        "[;)]": "ee_3.png",
        "[:-o]": "ee_4.png",
        "[:p]": "ee_5.png",
        "[(H)]": "ee_6.png",
        "[:@]": "ee_7.png"
    },
    map2: {
        "[:s]": "ee_8.png",
        "[:$]": "ee_9.png",
        "[:(]": "ee_10.png",
        "[:'(]": "ee_11.png",
        "[<o)]": "ee_12.png",
        "[(a)]": "ee_13.png",
        "[8o|]": "ee_14.png"
    },
    map3: {
        "[8-|]": "ee_15.png",
        "[+o(]": "ee_16.png",
        "[|-)]": "ee_17.png",
        "[:|]": "ee_18.png",
        "[*-)]": "ee_19.png",
        "[:-#]": "ee_20.png",
        "[^o)]": "ee_21.png",
        // "[del]": "del.png"
    },
    map4: {
        "[:-*]": "ee_22.png",
        "[8-)]": "ee_23.png",
        "[(|)]": "ee_24.png",
        "[(u)]": "ee_25.png",
        "[(S)]": "ee_26.png",
        "[(*)]": "ee_27.png",
        "[(#)]": "ee_28.png",
    },
    map5: {
        "[(R)]": "ee_29.png",
        "[({)]": "ee_30.png",
        "[(})]": "ee_31.png",
        "[(k)]": "ee_32.png",
        "[(F)]": "ee_33.png",
        "[(W)]": "ee_34.png",
        "[(D)]": "ee_35.png"
    },
    map6: {
        // "[del]": "del.png"
    }
};
// uni.connectSocket({url: WebIM.config.xmppURL, method: "GET"})

WebIM.conn = new WebIM.connection({
    appKey: WebIM.config.appkey,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
    https: typeof WebIM.config.https === "boolean" ? WebIM.config.https : location.protocol === "https:",
    url: WebIM.config.xmppURL,
    apiUrl: WebIM.config.apiURL,
    isAutoLogin: false,
    heartBeatWait: WebIM.config.heartBeatWait,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    autoReconnectInterval: WebIM.config.autoReconnectInterval,
    isDebug: false,
    isHttpDNS: false
});

WebIM.conn.addEventHandler('100', {
    onReceivedMessage: (message) => {
        console.log('收到消息送达服务器回执onCmdMessage: ', message)
    }, // 收到消息送达服务器回执。
    onDeliveredMessage: (message) => {
        console.log('收到消息送达客户端回执。onCmdMessage: ', message)
    }, // 收到消息送达客户端回执。
    onGroupChange: (msg) => {
        this.issendMsg = true
        console.log('++++++ijascas')
    },
})

WebIM.login = (username, password) => {
    return new Promise((resolve, reject) => {
        const options = {
            user: username, // 用户环信账号
            pwd: password, // 用户环信账号密码
            appKey: WebIM.config.appkey,
            success: (res) => {
                console.log(res, '环信登录成功')
                resolve(res)
            },
            error: (e) => {
                console.log(e.message, '登录失败')
                reject(e)
            },
        }
        WebIM.conn.open(options)
    })
}
// 图片转换
WebIM.emojiToImg = (msg) => {
    // console.log('Emoji', WebIM.Emoji.map[msg], msg, WebIM.Emoji)

    let m = {
        type: 0, // 0 普通消息 1 图片
        text: msg,
    };

    if (!!WebIM.Emoji.map[msg]) {
        m.type = 1
        m.text = WebIM.Emoji.path + WebIM.Emoji.map[msg]
    }

    return m
}

WebIM.sendMessage = (option) => {
    // 发送一条文本消息
    let id = WebIM.conn.getUniqueId();
    let msg = new WebIM.message('txt', id);
    msg.set(option);
    return WebIM.conn.send(msg.body);
}
// 获取历史记录
WebIM.history = (options) => {
    /*
    {
        targetId:'',
        chatType:'',0990
        pageSize,
    }
    * */
    return WebIM.conn.getHistoryMessages(options)
}

// 获取会话记录
WebIM.getConversationList = (options) => {
    return WebIM.conn.getConversationlist(options)
}

// 加入群聊
WebIM.joinGroup = (group_id) => {
    let addgroup = {
        groupId: group_id, // 群组ID
        message: 'I am Tom', // 请求信息
    }
    WebIM.conn.joinGroup(addgroup).then((res) => {
        console.log(res, '申请进群')
        /* WebIM.conn.setSilentModeForConversation({ // 屏蔽消息
            conversationId: group_id, // 需要频闭的id
            type: 'groupChat', // 频闭类型
            options: {
                paramType: 0,
                remindType: 'ALL'
            },
            success: (e) => {
                console.log('屏蔽成功 private text Success', e)
            }, // 对成功的相关定义，sdk会将消息id登记到日志进行备份处理
            fail: (e) => {
                console.log('屏蔽失败' + JSON.stringify(e))
            },
        }) */
    })
      .catch((res) => {
          /* this.$message({
              message: res.message,
              type: 'error',
          }) */
          console.log(res, '进群失败')
      })
}

// 图片上传
WebIM.uploadAndSend = (input, to) => {
    let id = WebIM.conn.getUniqueId(); // 生成本地消息id
    let msg = new WebIM.message('img', id); // 创建图片消息
    return new Promise((resolve, reject) => {
        let img_url;
        let option = {
            apiUrl: WebIM.config.apiURL,
            file: input,
            to, // 接收消息对象
            roomType: false,
            onFileUploadError: function(err) { // 消息上传失败
                console.error('图片发送失败！', err);
                reject(err)
            },
            onFileUploadComplete: function(res) { // 消息上传成功
                console.log('onFileUploadComplete', res);
                img_url = res.uri + "/" + res.entities[0].uuid;
            },
            success: function() { // 消息发送成功
                console.log('Success');
                //缓存发送数据
                console.log(img_url);
                resolve(img_url)
            },
            flashUpload: WebIM.flashUpload
        };
        msg.set(option);
        WebIM.conn.send(msg.body);
    })


}
// 账号密码生成 默认用户名是xiq+username,默认密码是xiq_psd_+username
WebIM.makeAuthMap = (mobile) => {
    return {
        user: `xiq${mobile}`,
        pwd: `xiq_psd_${mobile}`
    }
}

export default WebIM
